<template>
  <div>
    <el-card shadow="never" class="border-none mt--6">
      <div slot="header">
        <el-tabs v-model="currentWorkType">
          <el-tab-pane name="lesson">
            <template #label>
              课堂练习
              <el-badge :value="countByWorkType('lesson')" :max="99" size="mini"></el-badge>
            </template>
          </el-tab-pane>
          <el-tab-pane label="课后作业" name="home">
            <template #label>
              课后作业
              <el-badge :value="countByWorkType('home')" :max="99" size="mini"></el-badge>
            </template>
          </el-tab-pane>
        </el-tabs>

        <div class="flex-x gap-4 pt-2">
          <span>
            <vxe-input v-model="query.keyword" placeholder="搜索题目" size="medium" clearable
              @keyup.enter.native="filterByKeyword"></vxe-input>
          </span>
          <span>
            <el-button type="primary" plain size="small" @click="filterByKeyword" icon="el-icon-search"
              :loading="loading">搜索</el-button>
          </span>
          <span class="flex-1"></span>
          <span>
            <el-button type="success" size="small" @click="handleAddProblemBySelect" icon="el-icon-plus">
              添加编程题
            </el-button>
          </span>
          <span>
            <el-dropdown split-button type="primary" size="small" @click="handleAddNewQuestion"
              @command="handleAddQuestionBySelect">
              添加新习题
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="addQuestionBySelect">从习题库选择添加</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </span>
        </div>
      </div>

      <!-- Question Table -->
      <vxe-table ref="tableRef" stripe auto-resize :data="filteredQuestionList" :row-config="{drag: true}"
       @row-dragend="handleSortDragEnd"
      :loading="loading" align="center">
        <vxe-table-column field="id" title="ID" width="60"></vxe-table-column>
     
        <vxe-table-column field="questionType" title="题目类型" width="100">
          <template v-slot="{ row }">
            <question-type-tag :type="row.questionType" />
          </template>
        </vxe-table-column>

        <vxe-table-column field="title" title="题目" min-width="200">
          <template v-slot="{ row }">
            <div v-if="row.question">
              {{ row.question.content }}
            </div>
            <div v-if="row.problem">
              {{ row.problem.title }}
            </div>
          </template>
        </vxe-table-column>

        <vxe-table-column field="sortOrder" title="排序" width="80" drag-sort></vxe-table-column>
        <vxe-table-column field="gmtCreate" title="创建时间" width="150">
          <template v-slot="{ row }">
            {{ row.gmtCreate }}
          </template>
        </vxe-table-column>
        <vxe-table-column title="操作" width="80" fixed="right">
          <template v-slot="{ row }">         
            <el-tooltip effect="dark" content="删除" placement="top">
              <el-button plain circle type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(row)">
              </el-button>
            </el-tooltip>
          </template>
        </vxe-table-column>
      </vxe-table>

      <question-form-drawer ref="questionFormDrawer" @success="handleSaveQuestionSuccess" />

      <question-select-dialog ref="questionSelectDialog" @select="handleQuestionSelect" />

      <problem-select-dialog ref="problemSelectDialog" @select="handleProblemSelect" />
    </el-card>
  </div>
</template>

<script>
import api from '@/common/api';
import QuestionTypeTag from '@/components/admin/QuestionTypeTag.vue';
import QuestionFormDrawer from "@/views/admin/course/QuestionList/components/QuestionFormDrawer.vue";
import QuestionSelectDialog from "@/views/admin/course/LessonList/components/QuestionSelectDialog.vue";
import ProblemSelectDialog from "@/views/admin/course/LessonList/components/ProblemSelectDialog.vue";

export default {
  name: 'LessonWorkQuestionList',
  components: { QuestionFormDrawer, QuestionSelectDialog, ProblemSelectDialog, QuestionTypeTag },  
  props: {
    lessonId: {
      type: [String, Number],
      required: true
    },
    workType: {
      type: String,
      required: true
    }
  },
  mounted() {
    this.loadLessonWorkQuestionList();
  },
  data() {
    return {
      workTypes: [{ label: '课堂练习', value: 'lesson' }, { label: '课后作业', value: 'home' }],

      currentWorkType: this.workType,

      questionList: [],
      loading: false,
      query: {
        keyword: ''
      },

      questionForm: {
        lessonId: this.lessonId,
        questionId: null,
        problemId: null,
        questionType: null,
        workType: this.workType,
        sortOrder: 0
      },
      rules: {
        questionType: [
          { required: true, message: '请选择题目类型', trigger: 'change' }
        ],
        workType: [
          { required: true, message: '请选择作业类型', trigger: 'change' }
        ],
        sortOrder: [
          { required: true, message: '请输入排序号', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    filteredQuestionList() {
      return this.questionList.filter(item => item.workType === this.currentWorkType);
    }
  },
  methods: {
    loadLessonWorkQuestionList() {
      this.loading = true;
      api.admin_getLessonWorkQuestionList({ lessonId: this.lessonId, keyword: this.query.keyword }).then(res => {
        this.questionList = res.data.data;
      }).finally(() => {
        this.loading = false;
      });
    },
    countByWorkType(type) {
      return this.questionList.filter(item => item.workType === type).length;
    },
    filterByKeyword() {
      this.loadLessonWorkQuestionList();
    },    
    // 打开习题选择对话框
    handleAddQuestionBySelect() {
      const idArr = this.questionList.map(item => item.questionId)
      this.$refs.questionSelectDialog.open(idArr)
    },
    // 打开编程题选择对话框
    handleAddProblemBySelect() {
      const idArr = this.questionList.map(item => item.problemId).filter(id => id !== null)
      this.$refs.problemSelectDialog.open(idArr)
    },
    // 打开编辑对话框
    handleEdit(row) {     
      this.questionForm = { ...row };
    },
    handleDelete(row) {
      this.$confirm('确定要删除吗？', '提示', { type: 'warning' }).then(() => {
        api.admin_deleteLessonWorkQuestion(row.id).then(() => {
          this.loadLessonWorkQuestionList();
        });
      });
    },

    // 处理排序拖动结束
    async handleSortDragEnd() {
      const tableData = this.$refs.tableRef.getFullData()
      const idList = tableData.map(item => item.id)
      try {        
        this.loading = true
        await api.admin_updateLessonWorkQuestionSort({idList})
        await this.loadLessonWorkQuestionList()
      } finally {
        this.loading = false
      }
    },

    // 打开添加新习题对话框
    handleAddNewQuestion(mode) {
      const data = {workType:this.currentWorkType, lessonId: this.lessonId}
      this.$refs.questionFormDrawer.open(data)
    },
    // 保存新习题成功
    handleSaveQuestionSuccess() {
      this.loadLessonWorkQuestionList();
    },   

    // 处理习题选择
    handleQuestionSelect(id) {      
      this.addLessonWorkQuestion({questionId: id})
    },
    // 处理编程题选择
    handleProblemSelect(id) {
      this.addLessonWorkQuestion({problemId: id})
    },
    // 添加作业题目，questionId为习题id，problemId为编程题id，二选一即可
    async addLessonWorkQuestion({questionId, problemId}) {
      const data = {
        questionId,
        problemId,
        workType: this.currentWorkType,
        lessonId: this.lessonId
      }
      try {
        this.loading = true
        await api.admin_saveLessonWorkQuestion(data)
        this.loadLessonWorkQuestionList()
      } finally {
        this.loading = false
      }
    },
  }
}

</script>